package com.ktjiaoyu.crm;

import com.alibaba.fastjson.JSON;
import com.ktjiaoyu.crm.pojo.User;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

@SpringBootTest
public class JedisTester {

    private Jedis jedis;

    @BeforeEach
    public void setup(){
        //创建Jedis实例对象
        jedis = new Jedis("127.0.0.1",6379);
    }

    @Test
    public void testJedisSet(){
        //往redis中set一个key-value
        jedis.set("name","zhangsan");
    }

    @Test
    public void testJedisGet(){
        System.out.println(jedis.get("name"));
    }

    @Test
    public void testJedisOpsObject(){
        User user = new User("test","123");
        //使用FastJson将User对象转换成JSON格式字符串
        String userJson = JSON.toJSONString(user);
        jedis.set("user",userJson);
        //取出User字符串
        String userStr = jedis.get("user");
        User user1 = JSON.parseObject(userStr,User.class);
        System.out.println("user："+user1.getUsrName());
    }


    @Test
    public void testTransaction(){
        System.out.println("开启Redis事务");
        //开启事务
        Transaction transaction = jedis.multi();
        //添加数据到redis
        transaction.set("name","ktjiaoyu");
        //事务提交
        transaction.exec();
        //取消事务
        //transaction.discard();
        System.out.println("结束Redis事务");
    }


}
